<template>
  <div v-loading.lock="loading" class="base-content">
    <div class="basic-info">
      <el-form ref="queryForm" :inline="true" :model="queryForm">
        <el-form-item label="物料编号" prop="number">
          <el-input v-model="queryForm.number" placeholder="请输入物料编号" />
        </el-form-item>
        <el-form-item label="物料名称" prop="name">
          <el-input v-model="queryForm.name" placeholder="请输入物料名称" />
        </el-form-item>
        <el-form-item label="型号规格" prop="size">
          <el-input v-model="queryForm.size" placeholder="请输入型号规格" />
        </el-form-item>
        <el-form-item label="分类" prop="type">
          <el-select v-model.trim="queryForm.type" placeholder="请选择">
            <el-option label="全部" :value="-1" />
            <el-option
              v-for="item in type"
              :key="item.id"
              :label="item.name"
              :value="item.id"
            >
            </el-option>
          </el-select>
        </el-form-item>
        <el-form-item label="状态" prop="Status">
          <el-select v-model="queryForm.Status" placeholder="请选择" filterable>
            <el-option label="全部" :value="-1" />
            <el-option label="有效" :value="1" />
            <el-option label="无效" :value="2" />
          </el-select>
        </el-form-item>
        <el-form-item label="操作时间" prop="updateTimeRang">
          <el-date-picker
            v-model="queryForm.updateTimeRang"
            type="datetimerange"
            range-separator="至"
            start-placeholder="开始日期"
            end-placeholder="结束日期"
          >
          </el-date-picker>
        </el-form-item>
        <el-form-item>
          <el-button type="primary" @click="onQuery">查询</el-button>
          <el-button @click="cancelForm">清空</el-button>
        </el-form-item>
      </el-form>
      <div class="base-content-operate">
        <el-button type="primary" @click="onNew">新增</el-button>
        <el-button type="primary" @click="Export">导出</el-button>
        <el-button type="primary" @click="onSel">有效/无效</el-button>
        <el-button type="primary" @click="openPrintDialog"
          >打印条形码</el-button
        >
      </div>
      <el-table
        :data="list"
        height="250"
        fit
        highlight-current-row
        @selection-change="selectionChange"
      >
        <el-table-column type="selection" width="55"></el-table-column>
        <el-table-column label="物料编号" min-width="180">
          <template slot-scope="scope">
            <el-link
              size="mini"
              type="primary"
              @click="onView(scope.row)"
            >
              {{ scope.row.number }}</el-link
            >
          </template>
        </el-table-column>
        <el-table-column label="物料名称" min-width="120">
          <template slot-scope="scope">
            {{ scope.row.name }}
          </template>
        </el-table-column>
        <el-table-column label="物料别名" min-width="120">
          <template slot-scope="scope">
            {{ scope.row.aliasName }}
          </template>
        </el-table-column>
        <el-table-column label="分类" min-width="100">
          <template slot-scope="scope">
            {{ scope.row.typeName }}
          </template>
        </el-table-column>
        <el-table-column label="型号规格" min-width="120">
          <template slot-scope="scope">
            {{ scope.row.size }}
          </template>
        </el-table-column>
        <el-table-column label="包装单位" min-width="100">
          <template slot-scope="scope">
            {{ scope.row.packingUnit }}
          </template>
        </el-table-column>
        <el-table-column label="存储条件" min-width="100">
          <template slot-scope="scope">
            {{ scope.row.storeCondition }}
          </template>
        </el-table-column>
        <el-table-column label="实际库存" min-width="80">
          <template slot-scope="scope">
            {{ scope.row.inventory }}
          </template>
        </el-table-column>
        <el-table-column label="状态" min-width="80">
          <template slot-scope="scope">
            <span>{{ Status[scope.row.status] }}</span>
          </template>
        </el-table-column>
        <el-table-column label="操作人" min-width="80">
          <template slot-scope="scope">
            {{ scope.row.operator }}
          </template>
        </el-table-column>
        <el-table-column label="操作时间" sortable min-width="120">
          <template slot-scope="scope">
            {{ formatTimeMin(scope.row.updateTime) }}
          </template>
        </el-table-column>
        <el-table-column label="操作" min-width="120">
          <template slot-scope="scope">
            <div class="base-table-operation">
              <el-link size="mini" type="primary" @click="handleEdit(scope.row)"
                >编辑</el-link
              >
              <el-link
                size="mini"
                type="danger"
                @click="handleDelete(scope.row)"
                >删除</el-link
              >
            </div>
          </template>
        </el-table-column>
      </el-table>
      <BasePagination
        :total="pagination.total"
        :current-page="pagination.pageIndex"
        :page-count="pagination.total"
        @changePage="changePage"
        @sizeChange="sizeChange"
      />
    </div>
    <MaterialEdit
      v-if="dialogFormVisible"
      ref="MaterialEdit"
      :dialog-form-visible.sync="dialogFormVisible"
      :read-only.sync="readonly"
      :edit-id="editId"
      @success="onQuery"
    />
    <!-- 打印标签 -->
    <el-dialog
      v-toggle-full
      class="base-dialog"
      :custom-class="'panna-dialog_small'"
      title="设置标签大小"
      :append-to-body="true"
      :visible.sync="printDialogFormVisible"
      :before-close="closePrintDialog"
      ><el-form
        ref="printForm"
        :model="printForm"
        :rules="rules"
        label-width="80px"
      >
        <el-form-item label="宽" prop="labelWidth">
          <el-input
            v-model="printForm.labelWidth"
            size="small"
            onkeyup="this.value=this.value.match(/\d+\.?\d{0,2}/)"
            onafterpaste="this.value=this.value.match(/\d+\.?\d{0,2}/)"
            maxlength="4"
          ></el-input>
        </el-form-item>
        <el-form-item label="高" prop="labelHeight">
          <el-input
            v-model="printForm.labelHeight"
            size="small"
            onkeyup="this.value=this.value.match(/\d+\.?\d{0,2}/)"
            onafterpaste="this.value=this.value.match(/\d+\.?\d{0,2}/)"
            maxlength="4"
          ></el-input>
        </el-form-item>
      </el-form>
      <span slot="footer" class="base-dialog-footer">
        <el-button type="primary" @click="toPrint('printForm')">确定</el-button>
        <el-button @click="closePrintDialog">取 消</el-button>
      </span>
    </el-dialog>
    <div
      id="printDiv"
      ref="printDiv"
      style="display: none; width: 60mm; height: 40mm"
    >
      <div
        v-for="item in printData"
        :key="item.number"
        style="display: flex; flex-direction: column; align-items: center"
      >
        <img
          :src="
            item.number
              | creatBarCode(printForm.labelHeight, printForm.labelWidth)
          "
          style="max-width: 100%; max-height: 100%"
        />
      </div>
    </div>
    <iframe
      ref="printIframe"
      frameborder="0"
      scrolling="no"
      style="margin: 0px; padding: 0px; width: 0px; height: 0px"
    ></iframe>
  </div>
</template>

<script>
import { deleteRecord, getList, Status, getTreeData, updateStatus } from "../../../api/Material/Material.js";
import MaterialEdit from "./MaterialEdit.vue";
import { formatTimeMin } from "../../../utils/time"
import { export_json_to_excel } from "@/vendor/Export2Excel"
import BarcodeJs from 'jsbarcode';
export default {
  name: "MaterialList",
  components: { MaterialEdit },
  filters: {
    creatBarCode(barCodeData, labelHeight, labelWidth) {
      console.log("触发条码生成事件");
      const canvas = document.createElement("canvas");
      BarcodeJs(canvas, barCodeData, {
        format: "CODE128",
        displayValue: true,
        height: labelHeight,
        width: labelWidth,
        textAlign: "center",
        font: "cursive",
        fontOptions: "bold",
        fontSize: 30,
        textMargin: 3,
      });
      return canvas.toDataURL("image/png");
    }
  },
  data() {
    return {
      conTxt: "有效/无效",
      printData: [],
      tHeader: [
        "物料编号",
        "物料名称",
        "别名",
        "分类",
        "型号规格",
        "包装单位",
        "存储条件",
        "实际库存",
        "操作人",
        "操作时间",
        "状态"
      ],
      filterVal: [
        "number",
        "name",
        "aliasName",
        "typeName",
        "size",
        "packingUnit",
        "storeCondition",
        "inventory",
        "operator",
        "updateTime",
        "status"],
      editId: "",
      loading: true,
      readonly: false,
      list: [],
      type: [],
      Status,
      idList: [],
      queryForm: {
        number: "",
        name: "",
        size: "",
        type: -1,
        Status: -1,
        updateTimeRang: [],
        startUpdateTime: '',
        endUpdateTime: ''
      },
      dialogFormVisible: false,
      pagination: {
        pageIndex: 1,
        pageSize: 10,
        total: 0,
      },
      printDialogFormVisible: false,
      printForm: {
        labelWidth: "2",
        labelHeight: "80",
      },
      rules: {
        labelWidth: [
          { required: true, message: "请输入宽度", trigger: "blur" },
        ],
        labelHeight: [
          { required: true, message: "请输入高度", trigger: "blur" },
        ],
      },
    };
  },
  created() {
    this.getTreeDataFun()
    this.getList();
  },
  methods: {
    formatTimeMin,
    onSel() {
      if (this.idList.length <= 0) {
        this.$message.warning('请先选择需要更新的数据');
        return;
      }
      updateStatus({ id: this.idList }).then((res) => {
        if (res.code === 200) {
          this.getList();
        }
      }).catch(() => {
      });
    },
    openPrintDialog() {
      this.printForm.labelWidth = "2";
      this.printForm.labelHeight = "80";
      this.printDialogFormVisible = true;
    },
    closePrintDialog() {
      this.printDialogFormVisible = false;
      this.getList();
    },
    toPrint(form) {
      this.$refs[form].validate((valid) => {
        if (valid) {
          this.printTag();
        }
      });
    },
    printTag() {
      if (this.queryForm.updateTimeRang.length > 0) {
        this.queryForm.startUpdateTime = this.queryForm.updateTimeRang[0]
        this.queryForm.endUpdateTime = this.queryForm.updateTimeRang[1]
      } else {
        this.queryForm.startUpdateTime = ""
        this.queryForm.endUpdateTime = ""
      }
      getList(this.queryForm, { "pageIndex": 1, "pageSize": 10000 })
        .then((res) => {
          if (res.data.dataList.length <= 0) {
            this.$message.error('请选择需要打印的条形码');
            return;
          }
          this.printData = res.data.dataList;
          console.log(res);
          this.$nextTick(() => {
            var printIframe = this.$refs.printIframe;
            var html = this.$refs.printDiv.innerHTML;
            printIframe.setAttribute('srcdoc', html);
            printIframe.onload = function() {
              // 去掉iframe里面的dom的body的padding margin的默认数值
              printIframe.contentWindow.document.body.style.padding = '0px';
              printIframe.contentWindow.document.body.style.margin = '0px';
              // 开始打印
              printIframe.contentWindow.focus();
              printIframe.contentWindow.print();
            };
          })
        })
    },
    export_json_to_excel,
    formatJson(filterVal, jsonData) {
      return jsonData.map((v) =>
        filterVal.map((j) => {
          return v[j];
        })
      );
    },
    Export() {
      if (this.queryForm.updateTimeRang.length > 0) {
        this.queryForm.startUpdateTime = this.queryForm.updateTimeRang[0]
        this.queryForm.endUpdateTime = this.queryForm.updateTimeRang[1]
      } else {
        this.queryForm.startUpdateTime = ""
        this.queryForm.endUpdateTime = ""
      }

      getList(this.queryForm, { "pageIndex": 1, "pageSize": 10000 })
        .then((res) => {
          for (var i = 0; i < res.data.dataList.length; i++) {
            res.data.dataList[i].status = this.Status[res.data.dataList[i].status]
          }
          var data = this.formatJson(this.filterVal, res.data.dataList);
          export_json_to_excel({
            header: this.tHeader, // 表头
            data, // 数据
            filename: "物料列表", // 导出文件名
            autoWidth: true, // 导出宽度自动
            bookType: "xlsx", // 导出后缀
          });
        })
        .catch(() => {
          this.loading = false;
        });
    },
    getTreeDataFun() {
      var obj = {};
      obj.appId = 4000;
      getTreeData(obj).then(res => {
        this.type = res.data[0].children
      })
    },
    changePage(val) {
      this.pagination.pageIndex = val;
      this.getList();
    },
    sizeChange(val) {
      this.pagination.pageIndex = 1;
      this.pagination.pageSize = val;
      this.getList();
    },
    cancelForm() {
      this.$refs.queryForm.resetFields();
      this.pagination.pageIndex = 1;
      this.getList();
    },
    getList() {
      this.loading = true;

      if (this.queryForm.updateTimeRang.length > 0) {
        this.queryForm.startUpdateTime = this.queryForm.updateTimeRang[0]
        this.queryForm.endUpdateTime = this.queryForm.updateTimeRang[1]
      } else {
        this.queryForm.startUpdateTime = ""
        this.queryForm.endUpdateTime = ""
      }

      getList(this.queryForm, this.pagination)
        .then((res) => {
          this.list = res.data.dataList ? res.data.dataList : [];
          this.pagination.total = res.data.total;
          this.loading = false;
        })
        .catch(() => {
          this.loading = false;
        });
    },
    onNew() {
      this.readonly = false;
      this.editId = "";
      this.dialogFormVisible = true;
    },
    onView(rowData) {
      this.readonly = true;
      this.editId = rowData.id;
      this.dialogFormVisible = true;
    },
    handleDelete(rowData) {
      this.Helper.deleteConfirm(() => {
        this.loading = true;
        deleteRecord({ id: rowData.id })
          .then((res) => {
            this.getList();
            this.loading = false;
          })
          .catch(() => {
            this.loading = false;
          });
      });
    },
    handleEdit(rowData) {
      this.readonly = false;
      this.editId = rowData.id;
      this.dialogFormVisible = true;
    },
    // 选中列
    selectionChange(val) {
      this.idList = val.map(x => x.id).join(",");
    },
    onQuery() {
      this.pagination.pageIndex = 1;
      this.dialogFormVisible = false;
      this.getList();
    },
    // 关闭弹框清空id
    closeDialog() {
      this.editId = "";
      this.readOnly = false;
      this.getList();
    },
  },
};
</script>
